import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, InputNumber, Upload, Image, message, DatePicker, Radio, Switch } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { createBanner, updateBanner } from '@/services/contentManagementApi';
import { uploadImage } from '@/services/systemManagementApi';
import moment from 'moment';

const { RangePicker } = DatePicker;

interface BannerFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: CONTENT.BannerModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const BannerForm: React.FC<BannerFormProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>('');

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && initialValues) {
        const formData = {
          ...initialValues,
          time_range: initialValues.start_time && initialValues.end_time
            ? [moment(initialValues.start_time), moment(initialValues.end_time)]
            : undefined,
        };
        form.setFieldsValue(formData);
        setImageUrl(initialValues.image || '');
      } else {
        form.resetFields();
        setImageUrl('');
      }
    }
  }, [visible, mode, initialValues, form]);

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        image: imageUrl, // 优先使用表单字段值，回退到状态变量
        start_time: values.time_range?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
        end_time: values.time_range?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
      };

      // 移除time_range字段
      delete submitData.time_range;

      console.log('提交轮播图数据:', submitData);

      if (mode === 'create') {
        await createBanner(submitData);
        message.success('轮播图创建成功');  
      } else {
        await updateBanner(initialValues!.id, submitData);
        message.success('轮播图更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '轮播图创建失败' : '轮播图更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理图片上传
  const handleImageUpload = async (file: File) => {
    try {
      const response = await uploadImage(file);
      const uploadedUrl = response.data.url;
      setImageUrl(uploadedUrl);

      // 同时更新表单字段，确保验证通过
      form.setFieldsValue({
        image: uploadedUrl
      });

      message.success('图片上传成功');
      return false;
    } catch (error) {
      message.error('图片上传失败');
      return false;
    }
  };

  return (
    <Modal
      title={mode === 'create' ? '新建轮播图' : '编辑轮播图'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={700}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          position: 'home_top',
          status: 'active',
          sort_order: 0,
          link_type: 'none',
          is_new_window: false,
        }}
      >
        <Form.Item
          name="title"
          label="轮播图标题"
          rules={[
            { required: true, message: '请输入轮播图标题' },
            { max: 100, message: '标题不能超过100个字符' },
          ]}
        >
          <Input placeholder="请输入轮播图标题" />
        </Form.Item>

        <Form.Item
          name="description"
          label="描述"
          rules={[{ max: 200, message: '描述不能超过200个字符' }]}
        >
          <Input.TextArea
            rows={3}
            placeholder="请输入轮播图描述"
            showCount
            maxLength={200}
          />
        </Form.Item>

        {/* 隐藏的图片字段用于验证 */}
        <Form.Item
          name="image"
          rules={[{ required: true, message: '请上传轮播图片' }]}
          style={{ display: 'none' }}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="轮播图片"
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            {imageUrl && (
              <Image
                src={imageUrl}
                alt="轮播图"
                width={200}
                height={100}
                style={{ objectFit: 'cover', borderRadius: 4 }}
              />
            )}
            <Upload
              showUploadList={false}
              beforeUpload={handleImageUpload}
              accept="image/*"
            >
              <div style={{
                width: 200,
                height: 100,
                border: '1px dashed #d9d9d9',
                borderRadius: 4,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
              }}>
                <div style={{ textAlign: 'center' }}>
                  <PlusOutlined />
                  <div style={{ marginTop: 8, fontSize: '12px' }}>上传图片</div>
                  <div style={{ fontSize: '10px', color: '#999' }}>
                    建议尺寸: 750x375px
                  </div>
                </div>
              </div>
            </Upload>
          </div>
        </Form.Item>

        <Form.Item
          name="position"
          label="显示位置"
          rules={[{ required: true, message: '请选择显示位置' }]}
        >
          <Select placeholder="请选择显示位置">
            <Select.Option value="home_top">首页顶部</Select.Option>
            <Select.Option value="home_middle">首页中部</Select.Option>
            <Select.Option value="course_top">课程页顶部</Select.Option>
            <Select.Option value="activity_top">活动页顶部</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="sort_order"
          label="排序"
          rules={[
            { type: 'number', min: 0, message: '排序值不能为负数' },
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            placeholder="请输入排序值，数字越小越靠前"
            min={0}
          />
        </Form.Item>

        <Form.Item
          name="time_range"
          label="显示时间"
        >
          <RangePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            placeholder={['开始时间', '结束时间']}
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item
          name="link_type"
          label="链接类型"
          rules={[{ required: true, message: '请选择链接类型' }]}
        >
          <Radio.Group>
            <Radio value="none">无链接</Radio>
            <Radio value="url">外部链接</Radio>
            <Radio value="course">课程详情</Radio>
            <Radio value="activity">活动详情</Radio>
            <Radio value="page">页面跳转</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.link_type !== currentValues.link_type
          }
        >
          {({ getFieldValue }) => {
            const linkType = getFieldValue('link_type');
            
            if (linkType === 'url') {
              return (
                <Form.Item
                  name="link_url"
                  label="链接地址"
                  rules={[
                    { required: true, message: '请输入链接地址' },
                    { type: 'url', message: '请输入有效的URL地址' },
                  ]}
                >
                  <Input placeholder="请输入链接地址，如：https://example.com" />
                </Form.Item>
              );
            }
            
            if (linkType === 'course') {
              return (
                <Form.Item
                  name="link_course_id"
                  label="关联课程"
                  rules={[{ required: true, message: '请选择关联课程' }]}
                >
                  <Select placeholder="请选择关联课程">
                    {/* 这里应该从API获取课程列表 */}
                  </Select>
                </Form.Item>
              );
            }
            
            if (linkType === 'activity') {
              return (
                <Form.Item
                  name="link_activity_id"
                  label="关联活动"
                  rules={[{ required: true, message: '请选择关联活动' }]}
                >
                  <Select placeholder="请选择关联活动">
                    {/* 这里应该从API获取活动列表 */}
                  </Select>
                </Form.Item>
              );
            }
            
            if (linkType === 'page') {
              return (
                <Form.Item
                  name="link_page"
                  label="页面路径"
                  rules={[{ required: true, message: '请输入页面路径' }]}
                >
                  <Input placeholder="请输入页面路径，如：/about" />
                </Form.Item>
              );
            }
            
            return null;
          }}
        </Form.Item>

        <Form.Item
          name="is_new_window"
          label="新窗口打开"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Select.Option value="active">启用</Select.Option>
            <Select.Option value="inactive">禁用</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="alt_text"
          label="图片Alt文本"
          rules={[{ max: 100, message: 'Alt文本不能超过100个字符' }]}
        >
          <Input placeholder="请输入图片Alt文本，用于SEO和无障碍访问" />
        </Form.Item>

        <Form.Item
          name="keywords"
          label="关键词"
        >
          <Select
            mode="tags"
            placeholder="请输入关键词，用于搜索和分类"
            style={{ width: '100%' }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default BannerForm;
